#include "renderthread.h"
#include <QDebug>
#include <QPen>
#include <QBrush>
#include <QColor>

RenderThread::RenderThread(QObject *parent)
    : QObject(nullptr)  // 不设置parent，避免线程亲和性问题
    , m_thread(new QThread())  // 也不设置parent
    , m_renderTimer(nullptr)  // 在线程内创建，避免parent冲突
    , m_renderSize(800, 600)
    , m_running(false)
    , m_hasServerState(false)
    , m_currentFPS(0)
    , m_frameCount(0)
    , m_lastFPSTime(0)
    , m_lastRenderTime(0)
{
    Q_UNUSED(parent)  // 忽略parent参数

    // 初始化序列号为-1，避免"0 vs 0"的误判
    m_currentData.sequenceNumber = -1;

    // 连接线程信号，在线程内部设置定时器
    connect(m_thread, &QThread::started, this, [this]() {
        qDebug() << "RenderThread: 渲染线程已启动";
        qDebug() << "当前线程ID:" << QThread::currentThreadId();

        // 在正确的线程中创建定时器（无parent，避免线程冲突）
        m_renderTimer = new QTimer();
        m_renderTimer->setInterval(1000 / TARGET_FPS); // 60 FPS
        m_renderTimer->setTimerType(Qt::PreciseTimer); // 高精度定时器，稳定帧间隔
        connect(m_renderTimer, &QTimer::timeout, this, &RenderThread::renderFrame);

        m_lastFPSTime = QDateTime::currentMSecsSinceEpoch();
        m_renderTimer->start();

        qDebug() << "RenderThread: 定时器已启动(PreciseTimer)，活跃状态:" << m_renderTimer->isActive();
    });

    connect(m_thread, &QThread::finished, this, [this]() {
        qDebug() << "RenderThread: 渲染线程已停止";
        if (m_renderTimer) {
            m_renderTimer->stop();
            delete m_renderTimer;
            m_renderTimer = nullptr;
        }
    });
}

RenderThread::~RenderThread()
{
    // 安全地停止渲染线程
    if (m_running) {
        m_running = false;

        if (m_thread && m_thread->isRunning()) {
            m_thread->quit();
            if (!m_thread->wait(1000)) { // 等待1秒
                qWarning() << "RenderThread: 线程停止超时，强制终止";
                m_thread->terminate();
                m_thread->wait(500);
            }
        }
    }
}

void RenderThread::start()
{
    if (m_running) {
        return;
    }

    m_running = true;
    // 注意：不重置 m_hasServerState，保持之前的服务器状态
    // m_hasServerState 只在首次收到服务器数据时设置为 true
    m_frameCount = 0;
    m_lastFPSTime = QDateTime::currentMSecsSinceEpoch();

    qDebug() << "RenderThread: 启动渲染线程";

    // 在启动线程前，将自己移动到工作线程
    moveToThread(m_thread);

    m_thread->start();
    // 提高线程优先级，确保渲染节拍稳定
    m_thread->setPriority(QThread::HighPriority);
}

void RenderThread::stop()
{
    if (!m_running) {
        return;
    }

    m_running = false;

    qDebug() << "RenderThread: 停止渲染线程";

    // 等待线程结束
    if (m_thread->isRunning()) {
        m_thread->quit();
        m_thread->wait(3000);
    }
}

void RenderThread::setPriority(QThread::Priority priority)
{
    if (m_thread) {
        m_thread->setPriority(priority);
    }
}

void RenderThread::setRenderSize(const QSize &size)
{
    QMutexLocker locker(&m_dataMutex);
    m_renderSize = size;
}

void RenderThread::updateRenderData(const RenderReadyGameData &data)
{
    QMutexLocker locker(&m_dataMutex);

    qDebug() << "=== RenderThread::updateRenderData ===";
    qDebug() << "数据有效:" << data.isValid;
    qDebug() << "蛇身长度:" << data.snakeBody.size();
    qDebug() << "食物数量:" << data.foods.size();
    qDebug() << "时间戳:" << data.timestamp << "vs 当前:" << m_currentData.timestamp;
    qDebug() << "已有服务器状态:" << m_hasServerState;

    // 检查是否是首帧有效服务器数据
    if (!m_hasServerState && data.isValid && (data.snakeBody.size() > 0 || data.foods.size() > 0)) {
        qDebug() << "*** RenderThread: 首帧切换 - 收到首帧有效服务器数据 ***";
        qDebug() << "  服务器蛇身长度:" << data.snakeBody.size();
        qDebug() << "  服务器食物数量:" << data.foods.size();
        qDebug() << "  首帧序列号:" << data.sequenceNumber;
        m_hasServerState = true;
        qDebug() << "  设置hasServerState=true，后续将只渲染服务器数据";

        // 首帧强制更新，不检查序列号
        m_currentData = data;
        qDebug() << "首帧数据已强制更新到RenderThread";
    }
    else if (data.isValid && (
        (data.sequenceNumber > m_currentData.sequenceNumber) ||
        (data.sequenceNumber == 0 && m_currentData.sequenceNumber <= 0 && data.timestamp > m_currentData.timestamp))) {
        // 后续帧：优先使用序列号判断，如果序列号都是0或初始状态则回退到时间戳比较
        m_currentData = data;
        qDebug() << "数据已更新到RenderThread，序列号:" << data.sequenceNumber << "时间戳:" << data.timestamp;
    } else if (!data.isValid) {
        qDebug() << "数据被拒绝 - 数据无效";
    } else if (data.sequenceNumber == 0 && m_currentData.sequenceNumber == 0) {
        // 两个序列号都是0时，静默处理时间戳比较失败的情况
        qDebug() << "序列号都为0，时间戳未更新 (当前:" << m_currentData.timestamp << "收到:" << data.timestamp << ")";
    } else {
        qDebug() << "数据被拒绝 - 序列号过旧 (当前:" << m_currentData.sequenceNumber << "收到:" << data.sequenceNumber << ")";
    }
}

RenderReadyGameData RenderThread::getCurrentDataSnapshot() const
{
    QMutexLocker locker(&m_dataMutex);
    return m_currentData;
}

RenderCache RenderThread::getLatestFrame()
{
    QMutexLocker locker(&m_cacheMutex);
    return m_renderCache;
}

void RenderThread::renderFrame()
{
    if (!m_running) {
        return;
    }

    qint64 startTime = QDateTime::currentMSecsSinceEpoch();

    // 获取当前渲染数据
    RenderReadyGameData data;
    QSize renderSize;
    {
        QMutexLocker locker(&m_dataMutex);
        data = m_currentData;
        renderSize = m_renderSize;
    }
    // 准备双缓冲图像，避免每帧分配与跨线程 QPixmap
    if (m_backBuffer.size() != renderSize || m_backBuffer.format() != QImage::Format_ARGB32_Premultiplied) {
        m_backBuffer = QImage(renderSize, QImage::Format_ARGB32_Premultiplied);
    }
    m_backBuffer.fill(Qt::black);

    QPainter painter(&m_backBuffer);
    painter.setRenderHint(QPainter::Antialiasing, false);
    painter.setPen(QPen(Qt::NoPen));

    if (data.isValid) {
        renderGame(painter, data, renderSize);
    }
    painter.end();

    // 交换前后缓冲
    m_frontBuffer = m_backBuffer;

    // 更新渲染缓存（主线程使用 QPixmap 显示时再做轻量转换）
    {
        QMutexLocker locker(&m_cacheMutex);
        m_renderCache.gameFrame = QPixmap::fromImage(m_frontBuffer);
        m_renderCache.frameSize = renderSize;
        m_renderCache.timestamp = startTime;
        m_renderCache.isValid = true;
        m_renderCache.fps = m_currentFPS;
    }

    // 计算FPS
    m_frameCount++;
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    if (currentTime - m_lastFPSTime >= 1000) {
        m_currentFPS = m_frameCount;
        m_frameCount = 0;
        m_lastFPSTime = currentTime;
        emit fpsUpdated(m_currentFPS);
    }

    // 发送新帧信号（从 frontBuffer 转换）
    emit frameReady(QPixmap::fromImage(m_frontBuffer));

    // 发送渲染统计
    int renderTime = currentTime - startTime;
    if (m_frameCount % 60 == 0) { // 每60帧发送一次统计
        emit renderStats(renderTime, m_frameCount);
    }

    m_lastRenderTime = currentTime;
}

void RenderThread::renderGame(QPainter &painter, const RenderReadyGameData &data, const QSize &size)
{
    static int debugCount = 0;
    if (++debugCount % 60 == 1) { // 每秒输出一次
        qDebug() << "=== RenderThread::renderGame 调试 ===";
        qDebug() << "  m_hasServerState:" << m_hasServerState;
        qDebug() << "  data.snakeBody.size():" << data.snakeBody.size();
        qDebug() << "  data.foods.size():" << data.foods.size();
        qDebug() << "  data.isValid:" << data.isValid;
    }

    // 检查是否有有效的游戏数据
    if (!m_hasServerState || data.snakeBody.isEmpty()) {
        if (debugCount % 60 == 1) {
            qDebug() << "  → 渲染等待界面（原因：hasServerState=" << m_hasServerState
                     << " snakeBody.isEmpty=" << data.snakeBody.isEmpty() << ")";
        }
        // 显示等待服务器数据的界面
        renderWaitingScreen(painter, size);
        return;
    }

    if (debugCount % 60 == 1) {
        qDebug() << "  → 渲染游戏内容（蛇身=" << data.snakeBody.size() << " 食物=" << data.foods.size() << ")";
    }

    // 计算格子大小
    int cellSize = qMin(size.width() / data.mapWidth, size.height() / data.mapHeight);

    // 计算游戏区域偏移
    int offsetX = (size.width() - data.mapWidth * cellSize) / 2;
    int offsetY = (size.height() - data.mapHeight * cellSize) / 2;

    painter.translate(offsetX, offsetY);

    // 渲染背景网格
    renderGrid(painter, QSize(data.mapWidth * cellSize, data.mapHeight * cellSize), cellSize);

    // 渲染地图边界和障碍物
    renderMapElements(painter, data, cellSize);

    // 渲染食物
    renderFoods(painter, data.foods, cellSize);

    // 渲染蛇（预留插值管线：当前为直接渲染，可根据prev/curr与alpha插值）
    renderSnake(painter, data.snakeBody, cellSize);

    painter.resetTransform();

    // 渲染UI信息
    painter.setPen(Qt::white);
    painter.setFont(QFont("Arial", 16));
    painter.drawText(10, 30, QString("分数: %1").arg(data.score));
    painter.drawText(10, 60, QString("FPS: %1").arg(m_currentFPS));

    if (!data.alive) {
        painter.setPen(Qt::red);
        painter.setFont(QFont("Arial", 24, QFont::Bold));
        painter.drawText(size.width()/2 - 100, size.height()/2, "游戏结束");
    }
}

void RenderThread::renderSnake(QPainter &painter, const QList<QPoint> &snakeBody, int cellSize)
{
    if (snakeBody.isEmpty()) {
        return;
    }

    // 批量绘制蛇身矩形，减少 QPainter 调用次数
    if (snakeBody.size() > 1) {
        QVector<QRect> rects;
        rects.reserve(snakeBody.size() - 1);
        for (int i = 1; i < snakeBody.size(); ++i) {
            const QPoint &segment = snakeBody[i];
            rects.append(QRect(segment.x() * cellSize + 1, segment.y() * cellSize + 1,
                                cellSize - 2, cellSize - 2));
        }
        painter.setBrush(QColor(0, 200, 0));
        painter.setPen(QPen(Qt::green, 1));
        painter.drawRects(rects.constData(), rects.size());
    }

    // 渲染蛇头
    painter.setBrush(QColor(0, 255, 0));
    painter.setPen(QPen(Qt::darkGreen, 2));
    QPoint head = snakeBody.first();
    painter.drawEllipse(head.x() * cellSize + 2, head.y() * cellSize + 2,
                       cellSize - 4, cellSize - 4);

    // 渲染蛇身
    painter.setBrush(QColor(0, 200, 0));
    painter.setPen(QPen(Qt::green, 1));
    for (int i = 1; i < snakeBody.size(); ++i) {
        QPoint segment = snakeBody[i];
        painter.drawRect(segment.x() * cellSize + 1, segment.y() * cellSize + 1,
                        cellSize - 2, cellSize - 2);
    }
}

void RenderThread::renderFoods(QPainter &painter, const QList<QPoint> &foods, int cellSize)
{
    painter.setBrush(QColor(255, 0, 0));
    painter.setPen(QPen(Qt::darkRed, 1));

    // 使用路径批量绘制圆形，减少调用次数
    QPainterPath path;
    for (const QPoint &food : foods) {
        QRect r(food.x() * cellSize + 3, food.y() * cellSize + 3, cellSize - 6, cellSize - 6);
        path.addEllipse(r);
    }
    painter.drawPath(path);
}

void RenderThread::renderSnakeInterpolated(QPainter &painter, const QList<QPoint> &prev, const QList<QPoint> &curr, int cellSize, float alpha)
{
    // 简单线性插值：按同索引对齐，不足部分直接使用当前帧
    const int n = curr.size();
    QVector<QRectF> rects;
    rects.reserve(qMax(0, n - 1));

    // 身体段
    for (int i = 1; i < n; ++i) {
        QPointF c = curr[i];
        QPointF p = (i < prev.size()) ? QPointF(prev[i]) : c;
        QPointF pos = p + (c - p) * alpha;
        rects.append(QRectF(pos.x() * cellSize + 1, pos.y() * cellSize + 1,
                            cellSize - 2, cellSize - 2));
    }
    painter.setBrush(QColor(0, 200, 0));
    painter.setPen(QPen(Qt::green, 1));
    if (!rects.isEmpty()) painter.drawRects(rects.constData(), rects.size());

    // 头部
    QPointF ch = curr.isEmpty() ? QPointF() : QPointF(curr.first());
    QPointF ph = (!prev.isEmpty()) ? QPointF(prev.first()) : ch;
    QPointF headPos = ph + (ch - ph) * alpha;
    painter.setBrush(QColor(0, 255, 0));
    painter.setPen(QPen(Qt::darkGreen, 2));
    painter.drawEllipse(QRectF(headPos.x() * cellSize + 2, headPos.y() * cellSize + 2,
                               cellSize - 4, cellSize - 4));
}


void RenderThread::renderGrid(QPainter &painter, const QSize &size, int cellSize)
{
    static QImage gridCache;
    static QSize cachedSize;
    static int cachedCell = 0;

    if (gridCache.isNull() || cachedSize != size || cachedCell != cellSize) {
        gridCache = QImage(size, QImage::Format_ARGB32_Premultiplied);
        gridCache.fill(QColor(26, 26, 46));

        QPainter gp(&gridCache);
        gp.setPen(QPen(QColor(50, 50, 50), 1));
        for (int x = 0; x <= size.width(); x += cellSize) gp.drawLine(x, 0, x, size.height());
        for (int y = 0; y <= size.height(); y += cellSize) gp.drawLine(0, y, size.width(), y);
        gp.end();

        cachedSize = size;
        cachedCell = cellSize;
    }

    painter.drawImage(0, 0, gridCache);
}

void RenderThread::renderWaitingScreen(QPainter &painter, const QSize &size)
{
    // 设置背景色
    painter.fillRect(0, 0, size.width(), size.height(), QColor(26, 26, 46));

    // 绘制等待文本
    painter.setPen(Qt::white);
    painter.setFont(QFont("Arial", 24, QFont::Bold));

    QString waitingText = m_hasServerState ? "等待游戏数据..." : "正在连接服务器...";
    QFontMetrics fm(painter.font());
    QRect textRect = fm.boundingRect(waitingText);

    int x = (size.width() - textRect.width()) / 2;
    int y = (size.height() - textRect.height()) / 2;

    painter.drawText(x, y, waitingText);

    // 绘制加载动画（简单的旋转圆圈）
    static int rotationAngle = 0;
    rotationAngle = (rotationAngle + 10) % 360;

    painter.save();
    painter.translate(size.width() / 2, size.height() / 2 + 50);
    painter.rotate(rotationAngle);

    painter.setPen(QPen(Qt::cyan, 3));
    painter.drawArc(-20, -20, 40, 40, 0, 270 * 16); // 3/4 圆圈

    painter.restore();

    // 绘制提示信息
    painter.setFont(QFont("Arial", 14));
    painter.setPen(QColor(150, 150, 150));

    QString tipText = "请稍候，正在获取游戏数据...";
    QRect tipRect = fm.boundingRect(tipText);
    int tipX = (size.width() - tipRect.width()) / 2;
    int tipY = size.height() / 2 + 100;

    painter.drawText(tipX, tipY, tipText);
}

void RenderThread::renderMapElements(QPainter &painter, const RenderReadyGameData &data, int cellSize)
{
    // 渲染边界墙
    if (data.enableWalls) {
        painter.setBrush(QColor(255, 255, 255, 200));  // 半透明白色
        painter.setPen(QPen(Qt::white, 2));

        // 绘制四边边界
        int mapPixelWidth = data.mapWidth * cellSize;
        int mapPixelHeight = data.mapHeight * cellSize;

        // 上边界
        painter.drawRect(0, -2, mapPixelWidth, 2);
        // 下边界
        painter.drawRect(0, mapPixelHeight, mapPixelWidth, 2);
        // 左边界
        painter.drawRect(-2, 0, 2, mapPixelHeight);
        // 右边界
        painter.drawRect(mapPixelWidth, 0, 2, mapPixelHeight);
    }

    // 渲染障碍物
    if (!data.obstacles.isEmpty()) {
        painter.setBrush(QColor(128, 128, 128));  // 灰色障碍物
        painter.setPen(QPen(Qt::darkGray, 1));

        for (const QPoint &obstacle : data.obstacles) {
            QRect obstacleRect(obstacle.x() * cellSize + 1, obstacle.y() * cellSize + 1,
                              cellSize - 2, cellSize - 2);
            painter.drawRect(obstacleRect);
        }
    }
}

void RenderThread::forceImmediateRender()
{
    qDebug() << "RenderThread: 强制立即渲染（首帧落账）";

    // 立即触发一次渲染，不等定时器
    QMetaObject::invokeMethod(this, "renderFrame", Qt::QueuedConnection);
}
